package NetWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {

    private DatagramSocket socket = null;
    //抛出异常：1、端口号可能已经被占用了。2、每个进程能够打开的文件个数是有限的
    public UdpEchoServer(int port) throws SocketException {
        //此处在构造服务器这边的socket对象的时候，就需要显式的绑定一个端口号~
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器");
        while (true){
            //1、读取客户端发来的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);//为了接收数据需要先准备好一个空的DatagramPacket对象，由receive来进行填充数据
            //把DatagramPacket解析成一个String
            String request = new String(requestPacket.getData(),0,requestPacket.getLength(),"UTF-8");
            //2、根据请求计算响应
            String response = process(request);
            //3、把响应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req:%s,resp:%s\n",
                    requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
